/**
 * Created by 蔡健 on 2017/8/15.
 */

window.onload = function () {
	initWB();
	bindClickEvent();
};


var app = {};
var initWB = function () {
	var userAgent = navigator.userAgent;
	var platform = navigator.platform;

	app.gecko = /gecko\/\d/i.test(userAgent);
	app.ie_upto10 = /MSIE \d/.test(userAgent);
	app.ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
	app.ie = app.ie_upto10 || app.ie_11up;
	app.ie_version = app.ie && (app.ie_upto10 ? document.documentMode || 6 : app.ie_11up[1]);
	app.edge = /Edge\/(\d)/i.test(userAgent);
	app.firefox = /Firefox\/(\d)/i.test(userAgent);
	app.webkit = /WebKit\//.test(userAgent);
	app.qtwebkit = app.webkit && /Qt\/\d+\.\d+/.test(userAgent);
	app.chrome = /Chrome\//.test(userAgent);
	app.presto = /Opera\//.test(userAgent);
	app.safari = /Apple Computer/.test(navigator.vendor);
	app.mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
	app.phantom = /PhantomJS/.test(userAgent);

	app.ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
	// This is woefully incomplete. Suggestions for alternative methods welcome.
	app.mobile = app.ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
	app.mac = app.ios || /Mac/.test(platform);
	app.chromeOS = /\bCrOS\b/.test(userAgent);
	app.windows = /win/i.test(platform);

	if (app.ie_upto10 && app.ie_version < 10) {
		document.getElementById('root').innerHTML = '非常抱歉，此应用仅支持 Chrome、IE10+、Edge、360浏览器极速模式，请使用现代浏览器以获取最佳效果';
	}

};

var onShowLeftClick = function () {
	var left = $("#btnShowLeft");
	if (left.hasClass("icon-double-angle-left")) {
		//收缩/展开 图标改变
		left.removeClass("icon-double-angle-left");
		left.addClass("icon-double-angle-right");
		//隐藏图片列表
		$("#divLeftContent").hide(1000);
		//改变画布大小
		$("div.index-content").addClass("index-content-larger");
		$("div.index-left").addClass("index-left-small");
	} else {
		//与上面相反
		left.removeClass("icon-double-angle-right");
		left.addClass("icon-double-angle-left");
		$("#divLeftContent").show(1000);
		$("div.index-content").removeClass("index-content-larger");
		$("div.index-left").removeClass("index-left-small");
	}
};

var onKeyDown = function (event) {
	var keyCode = event.keyCode;
	//ctrl+v
	if (event.ctrlKey && keyCode == 86) {
		pastePic();
	}
	//删除 delete
	if (keyCode == 46) {
		if (selectedObjct.allSel.length > 0) {
			selectedObjct.allSel.forEach(function (currSelect) {
				removeSprite(currSelect);
			});
		} else {
			removeSprite(selectedObjct.currSel);
		}
	}
};

//取消当前选择
var deselectCurrent = function () {
	var selection = document.getSelection();
	if (!selection.rangeCount) {
		return function () {
		};
	}
	var active = document.activeElement;

	var ranges = [];
	for (var i = 0; i < selection.rangeCount; i++) {
		ranges.push(selection.getRangeAt(i));
	}

	switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
		case 'INPUT':
		case 'TEXTAREA':
			active.blur();
			break;

		default:
			active = null;
			break;
	}

	selection.removeAllRanges();
	return function () {
		selection.type === 'Caret' &&
		selection.removeAllRanges();

		if (!selection.rangeCount) {
			ranges.forEach(function (range) {
				selection.addRange(range);
			});
		}

		active &&
		active.focus();
	};
};

var copyImage, pastePolyfill;
var pastePic = function (e) {

	pastePolyfill = {
		retry: 0,
		range: document.createRange(),
		selection: document.getSelection(),
		reselectPrevious: deselectCurrent(),
		container: document.createElement('div'),
		reservedValue: ''
	};
	pastePolyfill.container.setAttribute('contentEditable', 'true');
	pastePolyfill.container.setAttribute('tabIndex', '-1');
	pastePolyfill.container.setAttribute('style', [
		'position: fixed',
		'clip: rect(0, 0, 0, 0)',
		'white-space: pre',
	].join(';'));

	document.body.appendChild(pastePolyfill.container);

	//删除所有焦点
	window.getSelection().removeAllRanges();

	pastePolyfill.range.selectNode(pastePolyfill.container);
	//获取焦点
	pastePolyfill.selection.addRange(pastePolyfill.range);
	pastePolyfill.container.focus();

	if (app.chrome || app.edge) {
		pastePolyfill.container.addEventListener('paste', webkitPaste);
	}

	// if (!(app.chrome || app.edge))
	// 	retryPolyfill()
};
var clearPolyfill = function () {
	try {
		if (pastePolyfill.selection) {
			if (typeof pastePolyfill.selection.removeRange == 'function') {
				pastePolyfill.selection.removeRange(pastePolyfill.range);
			} else {
				pastePolyfill.selection.removeAllRanges();
			}
		}
	} catch (e) {
	}

	if (pastePolyfill.container) {
		document.body.removeChild(pastePolyfill.container);
	}
	pastePolyfill.reselectPrevious();
}
function webkitPaste(e) {
	if (!(e.clipboardData && e.clipboardData.items)) {
		return;
	}

	for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
		var item = e.clipboardData.items[i];

		if (item.kind === "string") {
			item.getAsString(function (str) {
				// str 是获取到的字符串
			})
		} else if (item.kind === "file") {
			var pasteFile = item.getAsFile();
			console.log(pasteFile);
			// pasteFile就是获取到的文件
			var reader = new FileReader();
			reader.onload = function (evt) {
				copyImage = evt.currentTarget.result;
				sessionStorage.imageUrl = copyImage;
				window.loadPicture();
			};
			reader.readAsDataURL(pasteFile);
		}
	}
	clearPolyfill();
}

//是否正在剪切
var cutting = false;
//是否正在分割,是否图片里面进行分割
var chop = {chopping:false,chopInPic:false,chopOver:false};
//绑定按钮事件
var bindClickEvent = function () {

	//打开文件
	$('.icon-folder-open').closest('span').on('click', function () {
		$('#file_pic').trigger("click");
	});

    //裁剪
    $('.icon-magic').closest('span').on('click', function () {
    	if(selectedObjct.currSel == null){
    		alert("当前仅能对一张图片进行裁剪处理");
		}else{
            chop.chopping = true;
		}
    })

	//剪切
	$('.icon-cut').closest('span').on('click', function () {
		if (cutting) {
			cutting = false;
			$(this).css('color', '#5F5F5F')
		} else {
			cutting = true;
			$(this).css('color', '#108EE9')
		}
		cutPicture();
	});

	//组合
	$('.icon-cogs').closest('span').on('click', function () {
		combine();
	});

	//取消组合
	$('.icon-cog').closest('span').on('click', function () {
		cancelCombine();
	});

	//锁定
	$('.icon-lock').closest('span').on('click', function () {
		if (selectedObjct.allSel.length > 0) {
			selectedObjct.allSel.forEach(function (currSelect) {
				currSelect.ctrlMode = false;
				selectSprite(currSelect);
			});
		} else {
			selectedObjct.currSel.ctrlMode = false;
			selectSprite(selectedObjct.currSel);
		}
	});

	//解锁
	$('.icon-unlock').closest('span').on('click', function () {
		if (selectedObjct.allSel.length > 0) {
			selectedObjct.allSel.forEach(function (currSelect) {
				currSelect.ctrlMode = true;
				selectSprite(currSelect);
			});
		} else {
			selectedObjct.currSel.ctrlMode = true;
			selectSprite(selectedObjct.currSel);
		}
	});


	$('.icon-save').closest('span').on('click', function () {
		onSaveImageClick();
	});

};
function selectImage(obj) {
	var url = getFileUrl(obj.id);
	sessionStorage.imageUrl = url;
	window.loadPicture();
}

//将数据保存成图片
function onSaveImageClick() {
	if (selectedObjct.allSel.length > 0) {
		selectedObjct.allSel.forEach(function (currSelect) {
			cancelSelectSprite(currSelect);
		});
	} else {
		cancelSelectSprite(selectedObjct.currSel);
	}

	renderer.render(stage);
	renderer.view.toBlob(function (blob) {
		var newImg = document.createElement("img"),
			url = URL.createObjectURL(blob);
		newImg.style.marginLeft = "8px";
		newImg.onload = function () {
			// no longer need to read the blob so it's revoked
			URL.revokeObjectURL(url);
		};
		newImg.src = url;
		document.body.appendChild(newImg);
	});
}

